package com.mht.cfa.server.aop;//自己定义


import com.mht2017.common.consts.ResultCode;
import com.mht2017.common.response.BaseMessageResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * @author yutong.xiao
 * Date: 2018/6/6
 * Time: 18:04
 * Write an elegant code
 */

@Aspect
@Component
public class RequestAspect {
    //使用org.slf4j.Logger,这是Spring实现日志的方法
    private static final Logger logger = LoggerFactory.getLogger(RequestAspect.class);

    /**
     * 定义AOP扫描路径
     * 第一个注解只扫描aopTest方法
     */
    @Pointcut("execution(public * com.mht.demo.springboot.controller.*.*(..))")
    public void doRun() {
    }

    @Before("doRun()")
    public void doBefore(JoinPoint joinPoint) {
    }

    @Around("doRun()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        BaseMessageResponse baseMessageResponse = new BaseMessageResponse();
        //取参数如果没参数就不验证了
        Object[] objects = pjp.getArgs();
        if (objects.length != 0) {
            //寻找带BindingResult参数的方法，然后判断是否有error，如果有则是校验不通过
            for (Object object : objects) {
                if (object instanceof BeanPropertyBindingResult) {
                    BeanPropertyBindingResult result = (BeanPropertyBindingResult) object;
                    if (result.hasErrors()) {
                        List<ObjectError> list = result.getAllErrors();
                        for (ObjectError error : list) {
                            baseMessageResponse.setCode(ResultCode.PARAM_ERROR.getCode());
                            baseMessageResponse.setMessage(error.getDefaultMessage());
                            return baseMessageResponse;
                        }
                    }
                }
            }
        }
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            if (throwable.getMessage() != null) {
                baseMessageResponse.setMessage(throwable.getMessage());
            } else {
                baseMessageResponse.setMessage(throwable.getClass().getName());

            }
            return baseMessageResponse;
        }

    }

    /**
     * //     * 记录HTTP请求结束时的日志
     * //
     */
    @After("doRun()")
    public void doAfter() {

    }

    /**
     * 获取返回内容
     *
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "doRun()")
    public void doAfterReturn(Object object) {
    }
}